from ctypes import util
import numpy as np
import soundfile as sf
import os,json
import utils
import sys
import cv2
from tqdm import tqdm

from .task1_facelibrary import Facelibrary
from .task1_recognition import Recognition

class Task1Handler(Facelibrary,Recognition):
    def __init__(self):
        Facelibrary.__init__(self)
        self.face_list = ["ID1","ID10","ID11","ID12","ID13","ID14","ID15","ID16","ID17","ID18","ID19","ID2","ID20","ID3","ID4","ID5","ID6","ID7","ID8","ID9"] # 根据遍历顺序得到
    
    def returndic(self,video_path):
        #facelibrary = Facelibrary()
        self.mkdir("./dataset/task1/traindataset")
        for i in range(1,21,1):
            path = "./dataset/task1/traindataset/"+"ID{}".format(str(i))
            self.mkdir(path)    
        # 存储人脸库
        print('[Stage 2/4] Init Feature Lib')
        file_empty = 1
        for i in os.listdir("./dataset/task1/traindataset"):
            j = os.listdir("./dataset/task1/traindataset/"+str(i))
            file_empty = (file_empty and (not(len(j)==0)))
        
        if (len(os.listdir("./dataset/task1/featureMean/")) == 0):
            if (file_empty == 0):
                self.getframe()
            self.buildlibrary()

        # 测试时因为建立人脸库的时间较长，可以直接使用已经建立的人脸库

        # 测试1
        print('[Stage 3/4] Recognize Person')
        result_dict = {}
        for file_idx in tqdm(range(len(os.listdir(video_path))), ncols=70):
            file_name = os.listdir(video_path)[file_idx]
            # print("即将识别",file_name)
            ## 读取MP4文件中的视频,可以用任意其他的读写库
            cap=cv2.VideoCapture(video_path+'/'+file_name)
            frames_num = int(cap.get(7))
            frames_H = int(cap.get(4))
            frames_W = int(cap.get(3))
            video_frames = np.zeros((frames_num,frames_H,frames_W,3))
            if cap.isOpened():
                ret, frame = cap.read()
            else:
                ret = False
            #frame_interval = 30  # 截取图片间隔帧的数量
            frame_count = 0 # 帧计数
            # 循环读取帧
            while ret:
                video_frames[frame_count,:,:,:] = frame
                ret, frame = cap.read()
                frame_count += 1
            cap.release()
            #print(video_frames.shape)
            video_frames = video_frames.astype(np.uint8)
            
            #face_mean = task_1_recognition.face_recognition(video_frames)
            #result = task_1_recognition.Result(face_mean,face_feature_array)
            Maxindex = self.face_recognition(video_frames)
            #print(Maxindex)

            ## 返回一个ID
            result_dict[file_name]=self.face_list[Maxindex]
            # print("已经识别",file_name)
            # print("-------------------------------------------------")
            #print("{} is {}".format(file_name,face_list[Maxindex]))
        return result_dict